package com.example.mytayunapi.Service;

import com.example.mytayunapi.Mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    @Override
    public String saveAvatar(MultipartFile avatar, String userId) throws IOException {
        // 获取原始文件名和扩展名
        String originalFilename = avatar.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 生成新的文件名，使用userId和当前时间戳确保唯一性
        String newFileName = userId + "_" + System.currentTimeMillis() + fileExtension;

        // 定义文件存放路径
        String uploadDir = "C:/Users/1056/IdeaProjects/tayun-tayun/tayun-user-end/html/assets/imgs/aureole/";
        File uploadDirectory = new File(uploadDir);
        if (!uploadDirectory.exists()) {
            uploadDirectory.mkdirs();
        }

        // 保存文件到指定目录
        File destFile = new File(uploadDir + newFileName);
        avatar.transferTo(destFile);

        // 保存新头像路径到数据库
        String newAvatarPath = "assets/imgs/aureole/" + newFileName;
        fileMapper.updateUserAvatar(userId, newAvatarPath);

        return newAvatarPath;
    }

    @Override
    public String saveAvatar2(MultipartFile avatar, String School_degree, String Share_title, String category, String Share_content) throws IOException {
        String originalFilename = avatar.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 生成新的文件名，使用userId和当前时间戳确保唯一性
        String newFileName = School_degree + "_" + System.currentTimeMillis() + fileExtension;

        // 定义文件存放路径
        String uploadDir = "C:/Users/1056/IdeaProjects/tayun-tayun/tayun-user-end/html/assets/imgs/sharepicture/";
        File uploadDirectory = new File(uploadDir);
        if (!uploadDirectory.exists()) {
            uploadDirectory.mkdirs();
        }

        // 保存文件到指定目录
        File destFile = new File(uploadDir + newFileName);
        avatar.transferTo(destFile);

        // 保存新头像路径到数据库
        String newAvatarPath = "assets/imgs/sharepicture/" + newFileName;
        fileMapper.insertUser(School_degree,newAvatarPath,Share_title,category,Share_content);

        return newAvatarPath;
    }
}
